package org.example.shixiguanli.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.example.base.common.model.UserModel;
import org.example.base.common.service.UserService;
import org.example.core.enums.ApiResult;
import org.example.core.mysql.SearchPageResult;
import org.example.core.mysql.Where;
import org.example.shixiguanli.service.TPracticeLogService;
import org.example.shixiguanli.service.TPracticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * Date: 2024/2/16 00:06
 */
@RestController
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private UserService userService;

    @Autowired
    private TPracticeLogService tPracticeLogService;

    @Autowired
    private TPracticeService tPracticeService;

    /**
     * 筛选用户为当前教师下的所有用户
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/searchPage")
    public ApiResult searchPage(int page,int limit){
        SearchPageResult<JSONObject> result = new SearchPageResult<>();
        result.setPage(page);
        result.setLimit(limit);
        String userId = ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
        Where where = Where.build().field("teacher_user_id").equal(userId).and().field("del_flag").equal(0);
        result.setTotalCount(userService.count(where));
        List<UserModel> userModelList = userService.search(where.limit(page,limit));
        List<JSONObject> userModelJsonObjectList = new ArrayList<>();
        userModelList.stream().forEach(userModel -> {
            JSONObject userModelJsonObject = JSONUtil.parseObj(userModel);
            userModelJsonObject.set("practice",tPracticeService.searchOne(Where.build().field("user_id").equal(userId).and().field("del_flag").equal(0)));
            userModelJsonObject.set("practiceLog",tPracticeLogService.search(Where.build().field("user_id").equal(userId).and().field("del_flag").equal(0)));
            userModelJsonObjectList.add(userModelJsonObject);
        });
        result.setList(userModelJsonObjectList);
        return ApiResult.success(result);
    }
}
